<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SPI Agent Server API 测试工具</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
        }
        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
        }
        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }
        .main-panel {
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            padding: 30px;
        }
        .input-section {
            margin-bottom: 30px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }
        input, textarea, select {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s;
        }
        input:focus, textarea:focus, select:focus {
            outline: none;
            border-color: #667eea;
        }
        textarea {
            min-height: 100px;
            resize: vertical;
        }
        .button-group {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }
        button {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.4);
        }
        .btn-secondary {
            background: #f5f5f5;
            color: #333;
        }
        .btn-secondary:hover {
            background: #e0e0e0;
        }
        .examples {
            margin-top: 20px;
        }
        .example-chip {
            display: inline-block;
            padding: 8px 16px;
            margin: 5px;
            background: #f0f4ff;
            color: #667eea;
            border-radius: 20px;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 14px;
        }
        .example-chip:hover {
            background: #667eea;
            color: white;
        }
        .output-section {
            margin-top: 30px;
            padding-top: 30px;
            border-top: 2px solid #f0f0f0;
        }
        .response-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .status-badge {
            padding: 6px 12px;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 600;
        }
        .status-success {
            background: #d4edda;
            color: #155724;
        }
        .status-error {
            background: #f8d7da;
            color: #721c24;
        }
        .response-content {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            min-height: 200px;
        }
        .response-tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        .tab {
            padding: 8px 16px;
            background: white;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .tab.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        pre {
            background: white;
            padding: 15px;
            border-radius: 6px;
            overflow-x: auto;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            line-height: 1.5;
        }
        .summary-box {
            background: linear-gradient(135deg, #f0f4ff 0%, #f8f0ff 100%);
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .summary-box h3 {
            color: #667eea;
            margin-bottom: 10px;
        }
        .metadata-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }
        .metadata-item {
            background: white;
            padding: 12px;
            border-radius: 6px;
            text-align: center;
        }
        .metadata-label {
            font-size: 12px;
            color: #666;
            margin-bottom: 5px;
        }
        .metadata-value {
            font-size: 20px;
            font-weight: bold;
            color: #333;
        }
        .loading {
            text-align: center;
            padding: 40px;
        }
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 SPI Agent Server API 测试工具</h1>
            <p>智能自然语言查询服务 - 将您的问题转换为精确的数据查询</p>
        </div>

        <div class="main-panel">
            <div class="input-section">
                <h2 style="margin-bottom: 20px;">查询配置</h2>
                
                <div class="form-group">
                    <label for="baseUrl">服务地址</label>
                    <input type="text" id="baseUrl" value="http://localhost:5000" placeholder="http://localhost:5000">
                </div>

                <div class="form-group">
                    <label for="query">查询语句（自然语言）</label>
                    <textarea id="query" placeholder="例如：用户表有多少条记录">用户表有多少条记录</textarea>
                </div>

                <div class="form-group">
                    <label for="database">数据库名称（可选）</label>
                    <select id="database">
                        <option value="">默认数据库</option>
                        <option value="Main">Main</option>
                        <option value="Sales">Sales</option>
                        <option value="HR">HR</option>
                        <option value="Analytics">Analytics</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="sessionId">会话ID（可选）</label>
                    <input type="text" id="sessionId" placeholder="自动生成">
                </div>

                <div class="examples">
                    <label>快速示例：</label>
                    <span class="example-chip" onclick="setExample('用户表有多少条记录')">统计记录数</span>
                    <span class="example-chip" onclick="setExample('查看今天的订单数量')">今日订单</span>
                    <span class="example-chip" onclick="setExample('统计最近7天的销售额')">7天销售额</span>
                    <span class="example-chip" onclick="setExample('显示产品表的结构')">表结构</span>
                    <span class="example-chip" onclick="setExample('每个部门的平均工资')">部门统计</span>
                    <span class="example-chip" onclick="setExample('查找年龄大于30的用户')">条件查询</span>
                </div>

                <div class="button-group">
                    <button class="btn-primary" onclick="executeQuery()">执行查询</button>
                    <button class="btn-secondary" onclick="clearForm()">清空</button>
                    <button class="btn-secondary" onclick="testHealth()">健康检查</button>
                </div>
            </div>

            <div class="output-section" id="outputSection" style="display: none;">
                <div class="response-header">
                    <h2>查询结果</h2>
                    <span id="statusBadge" class="status-badge"></span>
                </div>

                <div id="loadingSection" class="loading" style="display: none;">
                    <div class="spinner"></div>
                    <p style="margin-top: 20px; color: #666;">正在处理查询...</p>
                </div>

                <div id="resultSection" style="display: none;">
                    <div id="summarySection" class="summary-box" style="display: none;">
                        <h3>查询摘要</h3>
                        <p id="summaryText"></p>
                    </div>

                    <div class="response-tabs">
                        <div class="tab active" onclick="switchTab('data')">数据结果</div>
                        <div class="tab" onclick="switchTab('raw')">原始响应</div>
                        <div class="tab" onclick="switchTab('sql')">执行的SQL</div>
                        <div class="tab" onclick="switchTab('metadata')">元信息</div>
                    </div>

                    <div class="response-content">
                        <div id="dataTab" class="tab-content active">
                            <div id="dataContent"></div>
                        </div>
                        <div id="rawTab" class="tab-content">
                            <pre id="rawContent"></pre>
                        </div>
                        <div id="sqlTab" class="tab-content">
                            <pre id="sqlContent"></pre>
                        </div>
                        <div id="metadataTab" class="tab-content">
                            <div class="metadata-grid" id="metadataContent"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        function setExample(query) {
            document.getElementById('query').value = query;
        }

        function clearForm() {
            document.getElementById('query').value = '';
            document.getElementById('sessionId').value = '';
            document.getElementById('database').value = '';
            document.getElementById('outputSection').style.display = 'none';
        }

        function switchTab(tabName) {
            // 移除所有活动状态
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });

            // 添加活动状态
            event.target.classList.add('active');
            document.getElementById(tabName + 'Tab').classList.add('active');
        }

        async function executeQuery() {
            const baseUrl = document.getElementById('baseUrl').value;
            const query = document.getElementById('query').value;
            const database = document.getElementById('database').value;
            const sessionId = document.getElementById('sessionId').value || `web-test-${Date.now()}`;

            if (!query) {
                alert('请输入查询语句');
                return;
            }

            // 显示加载状态
            document.getElementById('outputSection').style.display = 'block';
            document.getElementById('loadingSection').style.display = 'block';
            document.getElementById('resultSection').style.display = 'none';

            const requestBody = {
                query: query,
                sessionId: sessionId
            };

            if (database) {
                requestBody.databaseName = database;
            }

            try {
                const response = await fetch(`${baseUrl}/api/agent/query`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestBody)
                });

                const data = await response.json();

                // 隐藏加载状态
                document.getElementById('loadingSection').style.display = 'none';
                document.getElementById('resultSection').style.display = 'block';

                // 显示状态
                const statusBadge = document.getElementById('statusBadge');
                if (data.success) {
                    statusBadge.className = 'status-badge status-success';
                    statusBadge.textContent = '成功';
                } else {
                    statusBadge.className = 'status-badge status-error';
                    statusBadge.textContent = '失败';
                }

                // 显示摘要
                if (data.summary) {
                    document.getElementById('summarySection').style.display = 'block';
                    document.getElementById('summaryText').textContent = data.summary;
                } else {
                    document.getElementById('summarySection').style.display = 'none';
                }

                // 显示数据
                if (data.data) {
                    displayData(data.data);
                }

                // 显示原始响应
                document.getElementById('rawContent').textContent = JSON.stringify(data, null, 2);

                // 显示SQL
                if (data.metadata && data.metadata.executedSql) {
                    document.getElementById('sqlContent').textContent = data.metadata.executedSql;
                } else {
                    document.getElementById('sqlContent').textContent = '无SQL信息';
                }

                // 显示元信息
                if (data.metadata) {
                    displayMetadata(data.metadata);
                }

            } catch (error) {
                document.getElementById('loadingSection').style.display = 'none';
                document.getElementById('resultSection').style.display = 'block';
                
                const statusBadge = document.getElementById('statusBadge');
                statusBadge.className = 'status-badge status-error';
                statusBadge.textContent = '错误';

                document.getElementById('summarySection').style.display = 'block';
                document.getElementById('summaryText').textContent = `请求失败: ${error.message}`;
                
                document.getElementById('rawContent').textContent = error.toString();
            }
        }

        function displayData(data) {
            const container = document.getElementById('dataContent');
            
            if (!data || !data.rows || data.rows.length === 0) {
                container.innerHTML = '<p style="color: #666;">无数据返回</p>';
                return;
            }

            // 创建表格
            let html = '<table style="width: 100%; border-collapse: collapse;">';
            
            // 表头
            html += '<thead><tr style="background: #f0f0f0;">';
            for (const col of data.columns) {
                html += `<th style="padding: 10px; text-align: left; border-bottom: 2px solid #ddd;">${col}</th>`;
            }
            html += '</tr></thead>';
            
            // 表体
            html += '<tbody>';
            for (const row of data.rows) {
                html += '<tr>';
                for (const col of data.columns) {
                    html += `<td style="padding: 10px; border-bottom: 1px solid #eee;">${row[col] || ''}</td>`;
                }
                html += '</tr>';
            }
            html += '</tbody></table>';

            if (data.hasMore) {
                html += '<p style="margin-top: 10px; color: #666; font-style: italic;">结果已被限制，可能还有更多数据...</p>';
            }

            container.innerHTML = html;
        }

        function displayMetadata(metadata) {
            const container = document.getElementById('metadataContent');
            let html = '';

            if (metadata.executionTimeMs !== undefined) {
                html += `
                    <div class="metadata-item">
                        <div class="metadata-label">执行时间</div>
                        <div class="metadata-value">${metadata.executionTimeMs}ms</div>
                    </div>
                `;
            }

            if (metadata.rowCount !== undefined) {
                html += `
                    <div class="metadata-item">
                        <div class="metadata-label">返回行数</div>
                        <div class="metadata-value">${metadata.rowCount}</div>
                    </div>
                `;
            }

            if (metadata.usedTools && metadata.usedTools.length > 0) {
                html += `
                    <div class="metadata-item">
                        <div class="metadata-label">使用工具</div>
                        <div class="metadata-value" style="font-size: 14px;">${metadata.usedTools.join(', ')}</div>
                    </div>
                `;
            }

            if (metadata.sessionId) {
                html += `
                    <div class="metadata-item" style="grid-column: span 2;">
                        <div class="metadata-label">会话ID</div>
                        <div class="metadata-value" style="font-size: 12px; word-break: break-all;">${metadata.sessionId}</div>
                    </div>
                `;
            }

            container.innerHTML = html || '<p style="color: #666;">无元信息</p>';
        }

        async function testHealth() {
            const baseUrl = document.getElementById('baseUrl').value;
            
            try {
                const response = await fetch(`${baseUrl}/api/agent/health`);
                const data = await response.json();
                
                if (response.ok) {
                    alert(`服务状态：健康\n服务：${data.service}\n时间：${new Date(data.timestamp).toLocaleString()}`);
                } else {
                    alert('服务状态检查失败');
                }
            } catch (error) {
                alert(`无法连接到服务: ${error.message}`);
            }
        }

        // 页面加载时自动进行健康检查
        window.onload = function() {
            testHealth();
        };
    </script>
</body>
</html>







